<?php

namespace app\common\util;

class ArrayUtil
{
    public static function getArrayLeafNode($key, $array)
    {
        if (is_string($key)) {
            $params = explode('.', $key);
        } elseif (is_array($key)) {
            $params = $key;
        }
        $res = $array;
        foreach ($params as $param) {
            $res = $res[$param];
        }
        return $res;
    }

    public static function getOneInArray($array, $weightKey = 'weight')
    {
        $weights = array_column($array, $weightKey);
        $rand = rand(0, array_sum($weights));
        foreach ($array as $key => $item) {
            $rand -= $item[$weightKey];
            if ($rand <= 0) {
                return $array[$key];
            }
        }
    }

    public static function arrayToTree(array $data, $pid = 'pid', $label = 'name', $value = 'value', $disabled = 'status')
    {
        $data = array_column($data, null, $value);
        foreach ($data as $route) {
            if ($route[$pid]) {
                if (!isset($routes[$route[$pid]]['children'])) {
                    $routes[$route[$pid]]['children'] = [];
                }
                $routes[$route['pid']]['children'][] = [
                    'label' => $route[$label],
                    'value' => $route[$value],
                    'disabled' => !$route[$disabled]
                ];
            } else {
                $routes[$route['id']] = array_merge([
                    'label' => $route[$label],
                    'value' => $route[$value],
                    'disabled' => !$route[$disabled]
                ], $routes[$route[$value]] ?? []);
            }
        }
        $selectOption = [];
        foreach ($routes as $route) {
            $selectOption[] = $route;
        }
        return $selectOption;
    }
}